<template>
  <view class="search-container" :style="listHeightStylePage">
    <up-navbar title="查询聊天记录" @leftClick="searchforclose" placeholder></up-navbar>

    <!-- 搜索栏 -->
    <view class="search-bar">
      <up-input v-model="searchKeyword" placeholder="搜索" prefixIcon="search"
        prefixIconStyle="font-size: 22px;color: #909399;" @change="handleSearch"></up-input>
    </view>

    <!-- 筛选区域 -->
    <view class="search-filter">
      <view class="filter-tag" :class="{ active: selectedSender }" v-show="selectionList.length !== 0"
        @click="selectSender">
        <view class="avatar-container">
          <!-- 显示头像 -->
          <image v-if="selectionAvatarUrl" :src="selectionAvatarUrl" class="avatar-circle"></image>
          <view v-else class="avatar-title"> {{ selectionUsername }}</view>
          <!-- 如果有多人，显示 +N -->
          <text v-if="selectionCount > 1" class="avatar-count">+{{ selectionCount - 1 }}</text>
        </view>
      </view>


      <view class="filter-container">
        <uni-datetime-picker type="daterange" v-model="selectedDateRange" @change="handleDateChange" :border="false"
          class="compact-date-picker">
        </uni-datetime-picker>
      </view>

      <view v-if="searchKeyword || selection.length !== 0 || selectedDateRange.length !== 0" class="reset-button"
        @click="resetFilters">重置</view>
    </view>

    <!-- 搜索结果 -->

    <view style="padding-right: 20rpx;padding-left: 20rpx;padding-top: 20rpx;padding-bottom: 20rpx;">
      <scroll-view :refresher-background="'transparent'" class="search-result" :style="listHeightStyle"
        :scroll-top="scrollTop" scroll-y="true" :refresher-enabled="true" :refresher-triggered="isRefreshing"
        @refresherrefresh="onRefresh" @scrolltolower="loadMore">
        <view v-if="searchKeyword && searchResults.length === 0" class="no-result">
          <text>未找到相关记录</text>
        </view>
        <view v-else-if="searchResults" class="result-list">
          <view v-for="(item, index) in searchResults" :key="index" class="result-item">

            <!-- 头像和发送人 -->
            <view class="result-header">
              <view class="result-avatar">
                <image v-if="item.avatar" :src="item.avatar" class="avatar-circle"></image>
                <view v-else class="avatar-circle">{{ showUserName(item.username) }}</view>
              </view>
              <view class="result-sender">
                <text class="sender-name">{{ item.username }}</text>
                <text class="sender-time">{{ item.sendtime }}</text>
              </view>
            </view>

            <!-- 消息内容 -->
            <view class="result-content-box">


              <!-- 文本消息 -->
              <template v-if="item.type === 'text'">
                <up-parse :content="item.content"></up-parse>
              </template>

              <!-- 文件消息 -->
              <template v-else-if="item.type === 'file' || item.type === 'dir'">
                <view class="file-message" @click="openDoc(item)">
                  <view class="file-logo">
                    <image :src="`/static/fileType_big/${setFileIcon(item.name)}_b.png`" mode="widthFix"
                      style="width: 50rpx;"></image>
                  </view>
                  <view class="file-name">
                    <view>{{ item.name }}</view>
                    <text>{{ item.formatSize }}</text>
                  </view>
                </view>
              </template>
            </view>
            <view v-if="item.type === 'img' || item.type === 'img/text'" class="result-content-boximg">
              <!-- 图片消息 -->
              <template v-if="item.type === 'img'">
                <up-parse :content="item.content"></up-parse>
              </template>

              <!-- 图片消息 -->
              <template v-else-if="item.type === 'img/text'">
                <up-parse :content="item.content"></up-parse>
              </template>
            </view>


            <view v-if="item.type === 'apply'" class="chat-apply">
              <view class="apply-card">
                <view class="applytitle">
                  <view>
                    审批
                  </view>
                </view>
                <view class="apply-header">
                  <view class="apply-title">{{ item.apply.title }}</view>
                </view>
                <view class="apply-footer" @click="viewApplyDetail(item.apply.id)">
                  查看详情
                </view>
              </view>
            </view>

            <view v-if="item.type === 'apply_urge'" class="apply_urge">
              <view class="applyurge-card" @click="viewApplyDetail(item.content.id)">
                <view class="applyurgetitle"> {{ item.content.title }} </view>
                <!-- 标题和状态 -->
                <view class="applyurge-header">
                  <view style="padding-right: 5px;">
                    <image style="width: 45px;height: 45px;" src="@/static/appy-icon/download.png" alt="" />
                  </view>
                  <view class="applyurge-title">{{ item.content.content }}</view>
                </view>
              </view>
            </view>

            <view v-if="item.type === 'apply_mention'" class="apply_mention">
              <view class="applymention-card" @click="viewApplyDetail(item.content.id)">
                <view class="applymention-Title">
                  审批
                </view>
                <view class="applymentiontitle"> {{ item.content.title }} </view>
                <!-- 标题和状态 -->
                <view class="applymention-header">
                  <view class="applymention-title">{{ item.content.content }}</view>
                </view>
              </view>
            </view>

            <view v-if="item.type === 'log'" class="chat-log">
              <view class="log-card">
                <view class="log-bg">
                  <view class="log-title-top">日志</view>
                </view>
                <view class="log-title">{{ item.content.title }}</view>
                <view class="detail-btn" @click="viewLogDetail(item)">
                  查看详情
                </view>
              </view>
            </view>

            <view v-if="item.type === 'notice'" class="chat-notice">
              <view class="public-notice-card">
                <view class="notice-tag">公告</view>
                <view class="notice-title">{{ item.content.title }}</view>
                <view class="notice-content">{{ item.content.content }}</view>
              </view>
            </view>

          </view>
        </view>
        <view v-else class="no-result">
          <text>未找到相关记录</text>
        </view>

        <!-- 加载中提示 -->
        <view v-if="loading" class="loading-text">
          加载中...
        </view>

        <!-- 没有更多数据提示 -->
        <view v-if="noMore" class="no-more-text">
          没有更多数据了
        </view>
      </scroll-view>

    </view>

  </view>
</template>

<script>
import { chatApi } from '@/apis/cloud/chat';
import graceRichText from "@/pages/chat/message/config/rich-text-format.js";
import { useChatsettings, useChatStore, useGroupStore, useUserStore } from '@/pinia-store/user';
import { fileTypeFormat } from "@/utils/chat";
import { mapStores } from 'pinia';
export default {
  name: "Groupchathistory",
  data () {
    return {
      scrollTop: 0,
      searchKeyword: '',
      selectedSender: '',     // 已选择的发送人
      selectedTimeRange: '',   // 已选择的时间范围，如“最近一周”
      searchResults: [], // 搜索结果
      Chatarray: [],
      group: {},
      friend: null,
      imInfo: null,
      userInfo: null,
      dialogId: null,
      listHeight: 0, // 动态计算的高度
      listHeightStyle: {}, // 动态计算的样式
      topHeight: 0,
      listHeightStylePage: {},
      selectedDateRange: [],
      formattedDateRange: [],
      selection: [],
      isRefreshing: false,
      page: 1,
      loading: false,
      noMore: false,
      selectionList: [],
      nextCloud: {}
    }
  },
  computed: {
    ...mapStores(useChatStore, useUserStore, useGroupStore),
    // 获取头像 URL 和人数计数
    selectionAvatarUrl () {
      if (this.selection.length > 0) {
        return this.selection[0].avatar || ''; // 默认头像路径
      }
      return '';
    },
    selectionCount () {
      return this.selection.length;
    },
    // 获取第一个用户的用户名
    selectionUsername () {
      if (this.selection.length > 0) {
        return this.selection[0].username || ''; // 如果没有用户名，默认显示“未知用户”
      }
      return '发送人';
    },
  },
  onLoad () {

  },
  watch: {
    formattedDateRange (value) {
      if (!value) {
        this.filterMessages();
      }

    }
  },
  async created () {
    let Chatsettings = useChatsettings()
    this.selectionList = Chatsettings.$state.selection
    this.nextCloud = uni.getStorageSync('next_cloud');
    this.imInfo = this.chatStore.imInfo;// 当前登录用户
    this.userInfo = this.userStore.user;
    this.infoId = this.chatStore.imInfo.id
    this.group = this.groupStore.group;
    await this.Getxiaoxi()
    // this.searchResults = this.processAllMessages();

    uni.$off('Groupchathistory')
    // #ifdef H5
    this.listHeightStylePage = {
      height: `${window.innerHeight}px`,
    };
    // #endif

    // #ifdef APP-PLUS
    const res = uni.getSystemInfoSync();
    this.listHeight = res.windowHeight;
    this.listHeightStylePage = {
      height: `${res.windowHeight}px`,
    };

    // #endif
    this.calculateListHeight()
    uni.$on('Groupchathistory', (data) => {
      this.scrollTop = 0
      uni.showLoading({
        title: '加载中....'
      });
      this.selection = JSON.parse(data)
      this.handleSearch(this.searchKeyword);
      uni.hideLoading();
    })

  },
  methods: {
		viewLogDetail(value){
      uni.navigateTo({
        url: `/pages/chatlog/index?id=${value.id}`,
      });
		},
    viewNoticeDetail () {
      console.log('公告')
    },
    getStatusText (status) {
      switch (status) {
        case 1: return '审批中';
        case 2: return '已通过';
        case 3: return '已拒绝';
        case 4: return '已撤销';
        default: return '';
      }
    },
    viewApplyDetail (id) {
      uni.navigateTo({
        url: `/pages/apply/oaList/applyOrderDetail?id=${id}`
      })
    },
    openDoc (item2) {
      const type = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf'];
      const str = item2.name.split('.');
      const icon = str[str.length - 1];
      const that = this;
      let url = ''
      const xtoken = this.nextCloud.xtoken
      const fileName = encodeURIComponent(encodeURIComponent(item2.name)); // 双重编码
      const fileurl = encodeURIComponent(item2.url); // 单次编码
      if (type.indexOf(icon) != -1) {
        let previewUrl = ''
        if (xtoken) {
          previewUrl = `https://cloud.mfarmers.com/dist/previewDoc1.html?xtoken=${xtoken}&nc_id=${item2.nc_id ? item2.nc_id : ''}&fileName=${fileName}&type=mobile&user=${that.userStore.user.worker_id}&url=${fileurl}`
        } else {
          previewUrl = `https://cloud.mfarmers.com/dist/previewDoc1.html?fileName=${fileName}&type=mobile&user=${that.userStore.user.worker_id}&url=${fileurl}`
        }
        let encodedData = encodeURIComponent(JSON.stringify({ previewUrl }));
        url = `/pages/chat/message/common/previewDoc?data=${encodedData}`
      } else {
        url = `/pages/chat/message/common/downloadDoc?fileName=${fileName}&fileSize=${item2.formatSize}&url=${fileurl}`
      }

      uni.navigateTo({
        url: url
      })

    },
    // 文件图标处理
    setFileIcon (fileName) {
      const str = fileName.split('.');
      return fileTypeFormat(str[str.length - 1])
    },
    calculateListHeight () {
      const windowHeight = window.innerHeight; // 视口高度
      const topHeight = this.topHeight || 0; // 顶部安全高度
      const navbarHeight = 41; // 导航栏高度（假设为 44px）
      const tabsHeight = 120;
      // #ifdef APP-PLUS
      this.listHeightStyle = {
        // overflowY: 'hidden',
        height: `${this.listHeight - 190}px`,
      };
      // #endif

      // #ifdef H5
      const listHeight = windowHeight - topHeight - navbarHeight - tabsHeight;
      this.listHeightStyle = {
        height: `${listHeight}px`,
        overflowY: 'hidden',

      };
      // #endif
    },
    handleDateChange (e) {
      this.scrollTop = 0
      if (Array.isArray(e) && e.length === 2) {
        this.selectedDateRange = e;
        this.formattedDateRange = this.formatDateRangeForDisplay(e);
        this.filterMessages();
      } else {
        this.filterMessages();
        this.selectedDateRange = [];
        this.formattedDateRange = '';
        this.searchResults = this.processAllMessages();
      }
    },
    formatDateRangeForDisplay (dateRange) {
      if (!dateRange || dateRange.length !== 2) return '';

      const format = (dateStr) => {
        const date = new Date(dateStr);
        return `${date.getMonth() + 1}月${date.getDate()}日`;
      };

      return `${format(dateRange[0])}-${format(dateRange[1])}`;
    },
    filterMessages () {
      this.handleSearch(this.searchKeyword);
    },
    searchforclose () {
      uni.navigateBack();
    },
    selectSender () {
      let that = this
      uni.navigateTo({
        url: '/components/chat/components/Group/Groupchatmembers?source=Groupchathistory',
        success: function (res) {
          res.eventChannel.emit('Groupchathistory', {
            selection: JSON.stringify(that.selection),
          })
        }
      })
    },
    // 处理图片链接为富文本
    setImgUrl(content) {
      // 1. 首先检查 content 是否为字符串，如果不是，直接返回空字符串或进行其他处理
      if (typeof content !== 'string') {
        console.warn('setImgUrl 接收到的 content 不是一个字符串:', content);
        return ''; // 或者返回一个占位图片，例如: return '<p><img src="placeholder.png" /></p>';
      }

      if (this.isRichText(content)) {
        return graceRichText.format(content);
      } else {
        // 处理图片URL
        let processedUrl = content;

        // 处理没有域名的相对路径（以/uploads/开头）
        if (processedUrl.startsWith('/uploads/')) {
          processedUrl = 'https://chat.mfarmers.com:88' + processedUrl;
        } else if (processedUrl.startsWith('uploads/')) {
          processedUrl = 'https://chat.mfarmers.com:88/' + processedUrl;
        }

        // 处理有域名但端口是81的
        processedUrl = processedUrl.replace('http://chat.mfarmers.com:81/', 'https://chat.mfarmers.com:88/');

        // 处理有域名但没有端口的
        processedUrl = processedUrl.replace('http://chat.mfarmers.com/', 'https://chat.mfarmers.com:88/');

        // 移除thumb_前缀（如果存在）
        processedUrl = processedUrl.replace(/(\/)thumb_/g, '$1');

        // 确保URL使用HTTPS协议
        if (processedUrl.startsWith('http://')) {
          processedUrl = processedUrl.replace('http://', 'https://');
        }

        // 添加自适应样式
        return graceRichText.format(`<p><img src="${processedUrl}" style="max-width: 200rpx; height: auto;" /></p>`);
      }
    },
    // 判断是否为富文本
    isRichText (str) {
      return /<[a-z][\s\S]*>/i.test(str);
    },
    replaceAtSpan (html) {
      // 只匹配 class="mceNonEditable unfocusable" 的 span
      return html.replace(
        /<span\s+class="mceNonEditable unfocusable"(.*?)>(.*?)<\/span>/g,
        (match, attrs, inner) => {
          // 保留其他属性（例如 data=xxx）
          return `<span style="color: #409eff;"${attrs}>${inner}</span>`
        }
      );
    },
    extractPureText (html) {
      let pureText = '';

      // #ifdef H5
      const wrapper = document.createElement('div');
      wrapper.innerHTML = html;
      pureText = wrapper.textContent.trim();
      // #endif

      // #ifdef APP-PLUS
      // 替代 DOM 的正则方式：去掉所有标签，只留文本
      pureText = html.replace(/<[^>]+>/g, '').replace(/&nbsp;/g, '').trim();
      // #endif

      return pureText;
    },
    processAllMessages () {
      return this.Chatarray.reduce((result, item) => {
        if (item.status == 12) return result;
        let parsedContent;

        try {
          parsedContent = JSON.parse(item.content);
        } catch (e) {
          console.error('消息解析失败:', item.content);
          return result;
        }

        const baseData = {
          fromname: item.fromname,
          toname: item.to_name,
          sendtime: item.send_time,
          username: item.username,
          avatar: item.avatar,
          relation_type: item.relation_type, // 🔗 保留 reply 信息
          relation_id: item.relation_id
        };

        let processedMessages = [];

        // ✅ 情况 1：数组，且全是纯文本段落
        if (
          Array.isArray(parsedContent) &&
          parsedContent.every(msg => msg.type === 'text')
        ) {
          const mergedHtml = parsedContent.map(msg => msg.content).join('');
          const pureText = this.extractPureText(mergedHtml);

          if (pureText) {
            processedMessages.push({
              ...baseData,
              type: 'text',
              content: this.replaceAtSpan(pureText),
              rawContent: pureText
            });
          }
        }
        // ✅ 情况 2：数组，包含多种类型
        else if (Array.isArray(parsedContent)) {
          processedMessages = parsedContent.map(msg => {
            if (!msg.content || (typeof msg.content === 'string' && !msg.content.trim())) {
              return null;
            }

            switch (msg.type) {
              case 'text':
                return {
                  ...baseData,
                  type: 'text',
                  content: this.replaceAtSpan(msg.content),
                  rawContent: msg.content
                };
              case 'img':
                return {
                  ...baseData,
                  type: 'img',
                  content: this.setImgUrl(msg.content),
                  rawContent: msg.content
                };
              case 'img/text':
                return {
                  ...baseData,
                  type: 'img/text',
                  content: this.setHtmlContent(msg.content),
                  rawContent: msg.content
                };
              case 'file':
                return {
                  ...baseData,
                  type: 'file',
                  name: msg.name,
                  url: msg.url,
                  formatSize: msg.formatSize,
                  rawContent: msg.content
                };
              case 'apply':
                const applyData = JSON.parse(msg.content)
                return {
                  ...baseData,
                  type: 'apply',
                  apply: {
                    id: applyData.apply_id,
                    title: applyData.title,
                    status: applyData.status,
                    detail: applyData.detail
                  }
                };
              case 'apply_urge':
                const applyurgeData = JSON.parse(msg.content)
                return {
                  ...baseData,
                  type: 'apply_urge',
                  content: {
                    id: applyurgeData.apply_id,
                    title: applyurgeData.title,
                    content: applyurgeData.content,
                  }
                };
              case 'apply_mention':
                const applymentionData = JSON.parse(msg.content)
                return {
                  ...baseData,
                  type: 'apply_mention',
                  content: {
                    id: applymentionData.apply_id,
                    title: applymentionData.title,
                    content: applymentionData.content,
                  }
                };
              case 'log':
                const log = JSON.parse(msg.content)
                return {
                  ...baseData,
                  type: 'log',
                  id: log.id,
                  content: {
                    title: log.title,
                    content: log.content,
                  }
                };
              case 'notice':
                const notice = JSON.parse(msg.content)
                return {
                  ...baseData,
                  type: 'notice',
                  id: notice.id,
                  content: {
                    title: notice.title,
                    content: notice.content,
                  }
                };
              default:
                return null;
            }
          }).filter(Boolean);
        }
        // ✅ 情况 3：非数组，单个对象
        else if (parsedContent && parsedContent.type === 'text') {
          const raw = parsedContent.content;
          if (raw && raw.trim()) {
            processedMessages.push({
              ...baseData,
              type: 'text',
              content: this.replaceAtSpan(raw),
              rawContent: raw
            });
          }
        }

        return result.concat(processedMessages);
      }, []);
    },
    handleSearch (keyword) {
      this.scrollTop = 0
      const hasKeyword = keyword && keyword.trim() !== '';
      const hasSelection = this.selection.length > 0;
      const hasDateRange = this.selectedDateRange.length === 2;

      if (!hasKeyword && !hasSelection && !hasDateRange) {
        this.searchResults = this.processAllMessages();
        return;
      }

      // 否则执行筛选逻辑
      let filteredMessages = this.Chatarray.filter(item => {
        const sender = item.username || item.fromname;

        const keywordMatch = !hasKeyword ||
          this.getSearchableText(item.content).toLowerCase().includes(keyword.toLowerCase());

        const senderMatch = !hasSelection || this.selection.some(user => user.username === sender);
        return keywordMatch && senderMatch;
      });

      if (hasDateRange) {
        const [start, end] = this.selectedDateRange;
        const startDate = new Date(start);
        const endDate = new Date(end);
        endDate.setDate(endDate.getDate() + 1); // 包含结束当天

        filteredMessages = filteredMessages.filter(item => {
          const itemTime = new Date(item.send_time);
          return itemTime >= startDate && itemTime < endDate;
        });
      }

      const originalChatArray = this.Chatarray;
      this.Chatarray = filteredMessages;
      this.searchResults = this.processAllMessages();

      this.Chatarray = originalChatArray;
    },
    // 从消息内容中提取可搜索的文本
    getSearchableText (content) {
      try {
        const parsed = JSON.parse(content);
        if (!Array.isArray(parsed)) return '';

        return parsed.map(msg => {
          if (msg.type === 'text') {
            return this.extractPureText(msg.content)
          } else if (msg.type === 'file') {
            return msg.name || ''; // 文件名也可搜索
          }
          return '';
        }).join(' ');
      } catch (e) {
        console.error('解析消息失败:', e);
        return '';
      }
    },
    async resetFilters () {
      this.scrollTop = 0
      // 重置筛选条件
      this.searchKeyword = ''; // 清空搜索关键词
      this.selectedSender = ''; // 清空已选择的发送人
      this.selectedDateRange = []; // 清空时间范围
      this.selection = []; // 清空发送人选择
      this.page = 1;
      await this.Getxiaoxi()
      this.searchResults = this.processAllMessages();
    },
    // 名称超长处理
    showUserName (username) {
      if (username && username.length > 2) {
        return username.substr(1, 2);
      } else {
        return username;
      }
    },
    setHtmlContent (content) {
      try {
        // 处理图片URL
        let processedContent = content;

        // 处理没有域名的相对路径（以/uploads/或uploads/开头）
        processedContent = processedContent.replace(/(src=")(uploads\/)/g, '$1https://chat.mfarmers.com:88/$2');
        processedContent = processedContent.replace(/(src=")(\/uploads\/)/g, '$1https://chat.mfarmers.com:88$2');

        // 处理有域名但端口是81的
        processedContent = processedContent.replace(/http:\/\/chat\.mfarmers\.com:81\//g, 'https://chat.mfarmers.com:88/');

        // 处理有域名但没有端口的
        processedContent = processedContent.replace(/http:\/\/chat\.mfarmers\.com\//g, 'https://chat.mfarmers.com:88/');

        // 移除thumb_前缀（如果存在）
        processedContent = processedContent.replace(/(\/)thumb_/g, '$1');

        // 提取所有图片URL
        const imgTags = processedContent.match(/<img[^>]+>/g) || [];

        // 为每个图片添加自适应样式
        for (const imgTag of imgTags) {
          const newImgTag = imgTag.replace(
            /(<img[^>]*)(>)/,
            '$1 style="max-width: 200rpx; height: auto;"$2'
          );
          processedContent = processedContent.replace(imgTag, newImgTag);
        }

        // 使用graceRichText格式化
        return graceRichText.format(processedContent);
      } catch (e) {
        console.error(' 处理富文本内容失败:', e);
        return graceRichText.format(content);
      }
    },
    async onRefresh () {
      this.isRefreshing = true; // 开始刷新
      this.Chatarray = [];
      this.page = 1;
      this.noMore = false;
      // 调用获取消息的方法，带上查询条件
      await this.Getxiaoxi({
        searchKeyword: this.searchKeyword,
        selectedDateRange: this.selectedDateRange,
        selection: this.selection,
      });

      this.isRefreshing = false; // 结束刷新

    },
    async loadMore () {
      if (this.loading || this.noMore) return;
      this.page++;
      // 调用获取消息的方法，带上查询条件
      await this.Getxiaoxi({
        searchKeyword: this.searchKeyword,
        selectedDateRange: this.selectedDateRange,
        selection: this.selection,
      });
    },
    // 获取消息记录
    async Getxiaoxi ({ searchKeyword = '', selectedDateRange = [], selection = [] } = {}) {
      if (this.loading) {
        return
      }

      this.loading = true;

      uni.showLoading({
        title: '加载中....'
      });
      const params = {
        'data[groupId]': this.group.group_id,
        'data[account]': this.imInfo.account,
        'data[token]': this.userInfo.token,
        'data[myAccount]': this.imInfo.account,
        'data[page]': this.page,
        'data[pageSize]': 30,
        url: 'index.php/users/Group/getGroupChatRecord'
      }

      const msg = await chatApi(this.userInfo.token, params);

      if (msg.code == 200) {

        this.Chatarray = this.page == 1 ? msg.data.reverse() : [...this.Chatarray, ...msg.data.reverse()];

        if (msg.data.length == 0) {
          this.noMore = true;
        }
        this.isRefreshing = false;
        this.loading = false;
        uni.hideLoading();


        this.handleSearch(searchKeyword);
      } else {
        this.loading = false;
        this.noMore = true;
        this.isRefreshing = false;
        uni.hideLoading();
      }
      uni.hideLoading();
    },
  }
}
</script>

<style scoped lang="scss">
/* 加载中和无更多数据提示 */
.loading-text,
.no-more-text {
  margin-top: 20rpx;
  text-align: center;
  padding: 20rpx;
  color: #999;
  font-size: 28rpx;
}

// 聊天记录
.search-container {
  width: 100vw;
  background-color: #f3f3f3;
  overflow-y: hidden;

  .search-bar {
    padding: 20rpx;
    background-color: #ffffff;
    border-bottom: 1rpx solid #eee;
  }

  .search-filter {
    display: flex;
    padding: 0 20rpx;
    margin-top: 10rpx;

    .filter-tag {
      border: none;
      max-width: 18vw !important;
      background-color: #ffffff;
      border-radius: 10rpx;
      padding: 15rpx 30rpx;
      margin-right: 15rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 26rpx;
      color: #666;
      max-height: 36px !important;

      &:last-child {
        margin-right: 0;
      }

      &.active {
        color: #007AFF;
        border-color: #007AFF;
      }

      .tag-arrow {
        margin-left: 10rpx;

        :deep(.u-icon__icon) {
          font-size: 20rpx;
          color: #999;
        }
      }
    }

    .reset-button {
      width: 60px;
      color: #4498e6;
      font-size: 26rpx;
      // #ifdef H5
      padding: 15rpx 0rpx;
      // #endif
      // #ifdef APP-PLUS
      padding: 20rpx 0rpx;
      // #endif
      text-align: center;
      cursor: pointer;

      &:active {
        background-color: #f0faff;
      }
    }

    .filter-container {
      //#ifdef H5
      width: 61%;
      //#endif

      // #ifdef APP-PLUS
      width: 70%;
      // #endif
    }

  }

  .search-result {
    overflow-y: auto;

    .no-result {
      text-align: center;
      padding: 40rpx 0;
      color: #999;
      font-size: 26rpx;
    }

    .result-list {
      .result-item {
        border-radius: 20rpx;
        background-color: #ffffff;
        padding: 20rpx;
        margin-bottom: 20rpx;
        min-height: 80rpx;

        &:last-child {
          border-bottom: none;
        }

        .result-header {
          display: flex;
          align-items: center;
          margin-bottom: -30rpx;

          .result-avatar {
            margin-right: 20rpx;

            .avatar-circle {
              width: 80rpx;
              height: 80rpx;
              border-radius: 15%;
              background-color: #377fff;
              color: #fff;
              display: flex;
              justify-content: center;
              align-items: center;
              font-size: 32rpx;
              font-weight: bold;
            }
          }

          .result-sender {
            flex: 1;
            display: flex;
            flex-direction: column;

            .sender-name {
              font-size: 28rpx;
              color: #333;
              font-weight: bold;
              margin-bottom: 5rpx;
            }

            .sender-to {
              font-size: 24rpx;
              color: #666;
              margin-bottom: 5rpx;
            }

            .sender-time {

              font-size: 22rpx;
              color: #999;
              text-align: right;
              position: relative;
              // #ifdef H5
              top: -36rpx;
              // #endif

              // #ifdef APP-PLUS
              top: -36rpx;

              // #endif
            }
          }
        }

        .result-content-box {
          padding-left: 100rpx;

          .result-content {
            font-size: 26rpx;
            color: #333;
            line-height: 1.5;
          }
        }

        .result-content-boximg {
          margin-top: 12px;
          text-align: center;

          .result-content {
            font-size: 26rpx;
            color: #333;
            line-height: 1.5;
          }
        }
      }
    }
  }
}

.avatar-container {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center; // 水平居中

  .avatar-circle {
    width: 40rpx;
    height: 40rpx;
    background-color: #377fff;
    overflow: hidden;
  }

  .avatar-title {
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .avatar-count {
    position: absolute;
    right: -50rpx;
    bottom: 0;
    color: #000;
    font-size: 30rpx;
    padding: 5rpx 10rpx;
    border-radius: 50%;
    line-height: 1;
  }
}


.file-message {
  display: flex;

  .file-logo {
    margin-right: 20rpx;
    // #ifdef H5
    margin-top: 15rpx;
    // #endif

    // #ifdef APP-PLUS
    margin-top: 5rpx;
    // #endif
  }
}

// 审批单样式
.chat-apply {
  margin-top: 40rpx;
  display: flex;
  justify-content: center; // 水平居中
  width: 100%;

  .apply-card {
    width: 90%; // 限制宽度，居中效果更明显
    max-width: 600rpx;

    .applytitle {
      display: flex;
      font-weight: 600;
      background-color: #fff2e0;
      margin-bottom: 1px;
      padding: 8px;
      border-radius: 10px 10px 0px 0px;
      color: #fd9100;

      .apply-status {
        //#ifdef H5
        margin-top: 2rpx;
        //#endif

        // #ifdef APP-PLUS
        margin-top: -2rpx;
        // #endif
        height: 20px;
        line-height: 20px;
        text-align: center;
        max-width: 120rpx !important;
        min-width: 100rpx !important;
        margin-left: 12rpx;
        font-size: 12px;
        font-weight: 500;
        border-radius: 8px;
        color: #fff;
      }

      /* 审批状态：0 待提交 / 待处理 */
      .applystatus-0 {
        color: #ff9800;
        border: 1px solid #ff9800;
      }

      /* 审批状态：1 审核中 */
      .applystatus-1 {
        color: #2196f3;
        border: 1px solid #2196f3;
      }

      /* 审批状态：2 已通过 */
      .applystatus-2 {
        color: #4caf50;
        border: 1px solid #4caf50;
      }

      /* 审批状态：3 已驳回 */
      .applystatus-3 {
        color: #f44336;
        border: 1px solid #f44336;
      }

      /* 审批状态：4 已撤销 */
      .applystatus-4 {
        color: #9e9e9e;
        border: 1px solid #9e9e9e;
      }
    }

    border-radius: 16rpx;
    padding: 20rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

    .apply-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10rpx;

      .apply-title {
        font-size: 28rpx;
        color: #333;
        font-weight: bold;
      }


    }

    .apply-detail {
      margin-bottom: 10rpx;

      .apply-detail-item {
        display: flex;
        font-size: 26rpx;
        margin-bottom: 6rpx;

        .label {
          color: #666;
          width: 140rpx;
        }

        .value {
          color: #333;
          flex: 1;
        }
      }
    }

    .apply-footer {
      margin: 0 auto;
      width: 100%;
      background-color: #f3f3f4;
      margin-top: 10px;
      text-align: center;
      font-size: 28rpx;
      color: #0066ff;
      padding: 6px 0;
      border-radius: 8px;
      cursor: pointer;
      user-select: none;
      font-weight: 700;
    }
  }
}

.apply_urge {
  margin-top: 20rpx;
  display: flex;
  justify-content: center; // 水平居中
  width: 100%;

  .applyurge-card {
    background-color: #ffffff;
    border-radius: 8px;
    padding: 8px;
    margin: 8px 0;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.10);

    .applyurge-card {
      background-color: #ffffff;
      padding: 0px;
      border-radius: 10px;

      .applyurgetitle {
        font-weight: 600;
        padding: 4px;
      }
    }

    .applyurge-header {
      border: 1px solid #ddd;
      padding: 8px;
      border-radius: 5px;
      padding: 0 5px;
      display: flex;
      padding-top: 3px;
      border-radius: 5px;

      .applyurge-title {
        padding-top: 8rpx;
      }
    }
  }
}

.apply_mention {
  margin-top: 20rpx;
  display: flex;
  justify-content: center; // 水平居中
  width: 100%;

  .applymention-card {
    background-color: #ffffff;
    border-radius: 8px;
    padding: 8px;
    margin: 8px 0;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.10);

    .applymention-Title {
      font-weight: 600;
      background-color: #fff2e0;
      margin-bottom: 1px;
      padding: 8px;
      border-radius: 10px 10px 0px 0px;
      color: #fd9100;
    }

    .applymentiontitle {
      font-weight: 600;
      padding: 4px;
    }

    .applymention-header {
      padding: 8px;
      border-radius: 5px;
      padding: 0 5px;
      display: flex;
      padding-top: 3px;
      border-radius: 5px;

    }
  }
}

/* 日志消息样式 */
.chat-log {
  .log-card {
    position: relative;
    background: #c9e7ff;
    border-radius: 16rpx;
    padding: 2rpx;
    margin: 8rpx auto;
    width: 450rpx;
  }

  .log-bg {
    width: 95.5%;
    left: 0;
    top: 0;
    border-radius: 10px 10px 0px 0px;
    position: absolute;
    height: 30px;
    font-weight: bold;
    line-height: 30px;
    background-color: #e0ecff;
    color: #016fff;
    padding-left: 10px;
  }

  .log-title {
    margin-top: 60rpx;
    font-size: 30rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 15rpx;
    padding-left: 10px;
  }

  .log-content {
    font-size: 26rpx;
    color: #333;
    margin-bottom: 20rpx;
    line-height: 40rpx;
    padding-left: 10px;
  }

  .log-content ::v-deep p {
    margin: 0 0 10rpx 0;
    line-height: 1.6;
  }

  .log-content ::v-deep p:last-child {
    margin-bottom: 0;
  }
}

/* 通知消息样式 */
.chat-notice {
  .public-notice-card {
    background: #c9e7ff;
    border-radius: 16rpx;
    width: 450rpx;
    margin: 8rpx auto;
    padding: 2rpx;
  }

  .notice-tag {
    color: #66a6ff;
    margin-bottom: 10rpx;
    padding-left: 10px;
  }

  .notice-title {
    font-size: 30rpx;
    font-weight: bold;
    margin-bottom: 15rpx;
    color: #333;
    padding-left: 10px;
  }

  .notice-image {
    position: relative;
    margin-bottom: 15rpx;

    .image-text {
      position: absolute;
      left: 30rpx;
      top: 50%;
      transform: translateY(-50%);
      color: #fff;
      font-size: 36rpx;
    }

  }

  .notice-image image {
    width: 100%;
    border-radius: 8rpx;
  }

  .notice-content {
    font-size: 26rpx;
    color: #333;
    margin-bottom: 20rpx;
    line-height: 40rpx;
    padding-left: 10px;
  }
}

.detail-btn {
  margin: 0 auto;
  width: 100%;
  background-color: #f3f3f4;
  margin-top: 10px;
  text-align: center;
  font-size: 28rpx;
  color: #0066ff;
  padding: 6px 0;
  border-radius: 8px;
  cursor: pointer;
  user-select: none;
  font-weight: 700;
}
</style>
